#include <stdbool.h>
#include "enemy.h"
#include "box.h"
#include "room.h"
#include "utils.h"
#include <stdio.h>

void parseRooms(int width, int height, room_t *rooms){
    FILE *file;
    file = fopen("data/rooms.dta", "r");
    room_t maze[width][height];
    if (file) {
      char line [ 128 ]; /* or other suitable maximum line size */
      int x;
      int y;
      char seps[]   = ",\n";
      while ( fgets ( line, sizeof line, file ) != NULL ){
        //printf(line);
        //printf("\n");
        char * pch;
        //pch = strtok (line,seps);
        room_t *room = (room_t *)malloc(sizeof(room_t));
        if(!room){
            kill("Error de memoria.");
        }
        pch = strtok(line,seps);
        strcpy(room->here, pch);
        pch = strtok(NULL,seps);
        room->message = malloc(strlen(pch)+1);
        if(!room->message){
            kill("Error de memoria.");
        }
        strcpy(room->message, pch);
        room->block = booleanFromStr(strtok(NULL, seps));
        room->enemy = getEnemy((int)strtok(NULL, seps));
        room->objects = getBox((int)strtok(NULL, seps));
        pch = strtok (NULL, seps);
        int j = 0;
        while (pch != NULL){
            room->mov[j] = (char*)malloc(3*sizeof(char));
            if(!room->mov[j]){
                kill("Error de memoria.");
            }
            strcpy(room->mov[j],pch);
            pch = strtok (NULL, seps);
            j++;

        }
        sscanf(room->here, "%d.%d",&x,&y);
        maze[x][y] = *room;
        room = NULL;
        pch = NULL;
        free(room);
        free(pch);

    }
    rooms = &maze;

    room_t rom;
    rom = maze[0][0];
    printf("\n\n TEST \n");
    printf("here: %s\n", rom.here);
    printf("message: %s\n", rom.message);
    printf("block: %s\n", (rom.block)?"true":"false");
    int i;
    int elems = NELEMS(rom.mov);
    for(i=0; i<elems; i++){
       printf("mov[%d]: %s\n", i, rom.mov[i]);
    }
    rom = maze[0][1];
    printf("\n\n TEST \n");
    printf("here: %s\n", rom.here);
    printf("message: %s\n", rom.message);
    printf("block: %s\n", (rom.block)?"true":"false");
    elems = NELEMS(rom.mov);
    for(i=0; i<elems; i++){
       printf("mov[%d]: %s\n", i, rom.mov[i]);
    }

     //Intento acceder a la room atravez de la direccion de memoria.
    return(0);
    }else{
        kill("Hubo un problema con el archivo de configuracion. Porfavor vuelva a instalar el juego");
    }
   fclose(file);
}
